/*
 * create:2016年4月4日 下午6:36:10
 * author:wangds  
 */
package com.cxkj.shop.servlet;

import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import com.cxkj.shop.utils.WeiXinHttpsUtils;
import com.cxkj.shop.utils.WxUtils;

import net.wangds.common.GeneralParentObject;
//import net.wangds.common.context.BeanContext;
//import net.wangds.common.context.BeanContextFactory;
import net.wangds.comp.json.JsonUtil;
//import static net.wangds.precasting.context.Constants.SCHEMA_SPRING_PROVIDER;
import net.wangds.utilities.lang.StringUtils;

/**
 * .
 * 
 * @author wangds
 *
 */
public class RefreshTokenServlet extends HttpServlet {

  
  

  /**
   * RefreshTokenServlet.java.
   * @author wangds 2016年8月9日 下午3:38:22.
   */
  private static final long serialVersionUID = 7179703768384261137L;

  /*
   * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
   * @author wangds 2016年8月9日 下午3:42:45.
   */
  @Override
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    
    Runnable task = new Runnable() {
      
      @Override
      public void run() {
        try{
          while(true){
            String url = WxUtils.getRefreshTokenUrl();
            GeneralParentObject.staticLogger(this.getClass()).info(StringUtils.join("access \"",url,"\", fetch Weixin's token."));
            String json = WeiXinHttpsUtils.httpsGet(url);
            Map<String,Object> map = JsonUtil.toHashMap(json);
            String token = String.valueOf(map.get("access_token"));
            if(StringUtils.isEmpty(token)){
              try{
                Thread.sleep(5);
                continue;
              }catch(Exception e){
                GeneralParentObject.staticLogger(this.getClass()).error(e.getMessage(),e);
              }
            }
            
            GeneralParentObject.staticLogger(this.getClass()).info(StringUtils.join("Weixin's token will be set as \"",token,"\"."));
            WxUtils.setToken(token);
            int expires_in = ((Number)map.get("expires_in")).intValue();
            
            try{
              Thread.sleep(expires_in*1000/2);
            }catch(Exception e){
              GeneralParentObject.staticLogger(this.getClass()).error(e.getMessage(),e);
            }
          }
        }catch(Throwable t){
          GeneralParentObject.staticLogger(this.getClass()).error(t.getMessage(),t);
        }
      }
    };
    
    new Thread(task).start();
    
  }

}
